const express = require('express');
const router = express.Router();
// 引入刚才定义的表
const userModel = require('./../models/user');
const groupModel = require('./../models/group');
const response = require('../utils/response')
const { auth, SECRET } = require('../utils/auth')

const jwt = require('jsonwebtoken')
const bcrypt = require('bcryptjs');

/**
 * 这里是登录api
 * @route POST /user/login
 * @summary 用户login
 * @group user - 登录/注册/验证token
 * @param {User.model} user.body - user's info
 * @returns {object} 200 - An array of user info
 * @returns {Error}  default - Unexpected error
 */
router.post('/login', async (req, res, next) => {
  let { username, password } = req.body;

  // 根据用户名查找用户
  let user = await userModel.findOne({ username }).select('+password')

  // 用户不存在
  if (!user)
    return response(res, 1, '用户不存在')

  // 用户存在, 验证密码
  let isPassword = bcrypt.compareSync(password, user.password)
  // 密码错误
  if (!isPassword)
    return response(res, 1, '密码错误')

  // 登录成功, 生成token
  let token = jwt.sign({
    id: String(user._id)
  }, SECRET)
  // 返回token
  response(res, 0, '登录成功', { username, token })
});

/**
 * 这里是注册api
 * @route POST /user/signin
 * @summary 用户signin
 * @group user - 组注释
 * @param {User.model} user.body - user's info
 * @returns {object} 200 - An array of user info
 * @returns {Error}  default - Unexpected error
 */
router.post('/signin', async (req, res, next) => {
  let { username, password } = req.body;

  // 根据用户名查找用户
  let user = await userModel.findOne({ username }).select('+password')

  // 用户存在
  if (user)
    return response(res, 1, '用户已经存在')

  // 用户不存在, 存入数据库
  await userModel.create({ username, password })
  // 返回成功消息
  response(res, 0, "注册成功")
});

/**
 * 这里是验证api
 * @route GET /user/auth
 * @summary 用户auth
 * @group user - 组注释
 * @returns {object} 200 - An array of user info
 * @returns {Error}  default - Unexpected error
 * @security JWT
 */
router.get('/auth', auth, async (req, res, next) => {
  response(res, 0, "验证成功")
});

/**
 * 这里是获取用户信息api
 * @route GET /user/info
 * @summary 用户info
 * @group user - 组注释
 * @returns {object} 200 - An array of user info
 * @returns {Error}  default - Unexpected error
 * @security JWT
 */
router.get('/info', auth, async (req, res) => {
  console.log(req.tokenRes);

  let _id = req.tokenRes.id;
  let user = await userModel.findOne({ _id }, {
    'username': 1,
    'avatar': 1,
    'gender': 1,
    'birthday': 1,
  }).populate('group')

  // userModel.findOne({ _id }).populate('group').then(result => {
  //   response(res, 0, "成功", result)
  // })

  response(res, 0, "成功", user)
});

/**
 * 这里是更新用户信息api
 * @route POST /user/update
 * @summary 用户update
 * @group user - 组注释
 * @param {UserData.model} userdata.body - user's info
 * @returns {object} 200 - An array of user info
 * @returns {Error}  default - Unexpected error
 * @security JWT
 */
router.post('/update', auth, async (req, res, next) => {
  console.log(req.body);
  let _id = req.tokenRes.id;
  let data = req.body;
  await userModel.updateOne({ _id }, { ...data })
    .then(result => response(res, 0, "修改成功"))
    .catch(error => next(error))
});

/**
 * 这里是不需要token的api
 * @route GET /user/notoken
 * @summary 用户info
 * @group user - 组注释
 * @returns {object} 200 - An array of user info
 * @returns {Error}  default - Unexpected error
 */
router.get('/notoken', async (req, res) => {
  response(res, 0, "gaga")
});

/**
 * @typedef User
 * @property {string} username.required - username
 * @property {string} password.required - password
 */

/**
 * @typedef UserData
 * @property {string} avatar - avatar
 * @property {number} gender - gender
 * @property {string} birthday - gender
 * @property {string} emaill - emaill
 */

module.exports = router;
